package com.edu.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 设置允许跨域和设置开启Cookie
 * 描述：
 * 创建人：飘
 * 创建时间：2024/10/30
 **/
@WebFilter("/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //注意：这里设置只允许http://localhost:8081进行跨域访问
        //设置允许跨域
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        //设置开启Cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许 get,post,delete,put等方式请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
       //超时时间
        response.setHeader("Access-Control-Max-Age", "3628800");
        //开启验证
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        //放行
        chain.doFilter(req, resp);
    }
    @Override
    public void destroy() {}
}
